import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:family_app/src/common/constants.dart';
import 'package:family_app/src/features/auth/providers/auth_provider.dart';
import 'package:family_app/src/features/home/screens/home_screen.dart';
import 'package:family_app/src/theme/app_theme.dart';

/// 登录界面
class LoginScreen extends ConsumerStatefulWidget {
  const LoginScreen({Key? key}) : super(key: key);

  @override
  ConsumerState<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends ConsumerState<LoginScreen> {
  final _phoneController = TextEditingController();
  final _codeController = TextEditingController();
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  final _formKey = GlobalKey<FormState>();
  Timer? _countdownTimer;
  int _countdown = 60;
  bool _isCountingDown = false;
  bool _isPasswordVisible = false;
  String? _captchaToken;
  bool _captchaVerified = false;

  @override
  void dispose() {
    _phoneController.dispose();
    _codeController.dispose();
    _usernameController.dispose();
    _passwordController.dispose();
    _countdownTimer?.cancel();
    super.dispose();
  }

  /// 发送验证码
  Future<void> _sendVerificationCode() async {
    if (_phoneController.text.isEmpty || _phoneController.text.length != 11) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请输入正确的手机号')),
      );
      return;
    }

    // 更新发送状态
    ref.read(sendCodeStateProvider.notifier).state =
        const SendCodeState.sending();

    // 调用发送验证码接口
    final success =
        await ref.read(authStateProvider.notifier).sendVerificationCode(
              _phoneController.text,
            );

    if (success) {
      // 开始倒计时
      setState(() {
        _isCountingDown = true;
        _countdown = 60;
      });

      _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
        setState(() {
          if (_countdown > 1) {
            _countdown--;
          } else {
            _isCountingDown = false;
            timer.cancel();
          }
        });
      });

      // 更新状态为已发送
      ref.read(sendCodeStateProvider.notifier).state =
          SendCodeState.sent(_countdown);
    } else {
      // 更新状态为发送失败
      ref.read(sendCodeStateProvider.notifier).state =
          const SendCodeState.error('验证码发送失败，请稍后重试');
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('验证码发送失败，请稍后重试')),
      );
    }
  }

  /// 手机号验证码登录
  Future<void> _loginWithPhone() async {
    // 开发模式：跳过校验，直接进入首页
    if (mounted) {
      Navigator.of(context).pushReplacement(
        MaterialPageRoute(builder: (context) => const HomeScreen()),
      );
    }
  }
  
  /// 账号密码登录
  Future<void> _loginWithPassword() async {
    // 开发模式：跳过校验，直接进入首页
    if (mounted) {
      Navigator.of(context).pushReplacement(
        MaterialPageRoute(builder: (context) => const HomeScreen()),
      );
    }
  }
  
  /// 显示滑块验证码
  void _showCaptcha() {
    // 模拟滑块验证码验证成功
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('滑块验证'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('请按住滑块，拖动到最右边完成验证'),
            const SizedBox(height: 16),
            // 简单模拟滑块验证码
            StatefulBuilder(
              builder: (context, setState) {
                return Column(
                  children: [
                    SliderTheme(
                      data: SliderThemeData(
                        trackHeight: 40.h,
                        thumbShape: SliderComponentShape.noThumb,
                        overlayShape: SliderComponentShape.noOverlay,
                        valueIndicatorShape: SliderComponentShape.noOverlay,
                        trackShape: const RectangularSliderTrackShape(),
                      ),
                      child: Slider(
                        value: _captchaToken == null ? 0.0 : 1.0,
                        onChanged: (value) {
                          if (value >= 0.99) {
                            setState(() {
                              _captchaToken = DateTime.now().millisecondsSinceEpoch.toString();
                            });
                          }
                        },
                        activeColor: Colors.green,
                        inactiveColor: Colors.grey[200],
                      ),
                    ),
                    const SizedBox(height: 8),
                    _captchaToken != null
                        ? const Icon(Icons.check_circle, color: Colors.green)
                        : const SizedBox(),
                  ],
                );
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: _captchaToken == null
                ? null
                : () {
                    setState(() {
                      _captchaVerified = true;
                    });
                    Navigator.pop(context);
                  },
            child: const Text('确认'),
          ),
        ],
      ),
    );
  }

  /// 微信登录
  Future<void> _loginWithWeChat() async {
    final success =
        await ref.read(authStateProvider.notifier).loginWithWeChat();

    if (success) {
      if (mounted) {
        // 登录成功，跳转到首页
        Navigator.of(context).pushReplacement(
          MaterialPageRoute(builder: (context) => const HomeScreen()),
        );
      }
    } else {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('微信登录失败，请稍后重试')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final authState = ref.watch(authStateProvider);
    final sendCodeState = ref.watch(sendCodeStateProvider);
    final loginMethod = ref.watch(loginMethodProvider);

    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Center(
          child: SingleChildScrollView(
            padding: EdgeInsets.symmetric(horizontal: 24.w),
            child: Form(
              key: _formKey,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  // Logo 和标题
                  Icon(
                    Icons.family_restroom_rounded,
                    size: 80.r,
                    color: AppTheme.primaryColor,
                  ),
                  SizedBox(height: 16.h),
                  Text(
                    AppConstants.appName,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: 28.sp,
                      fontWeight: FontWeight.bold,
                      color: AppTheme.textPrimaryColor,
                    ),
                  ),
                  SizedBox(height: 8.h),
                  Text(
                    '您的家庭助手，让生活更简单',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: AppTheme.textSecondaryColor,
                    ),
                  ),
                  SizedBox(height: 32.h),
                  
                  // 登录方式切换
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      _buildLoginMethodButton(
                        title: '验证码登录',
                        isSelected: loginMethod == LoginMethod.phone,
                        onTap: () => ref.read(loginMethodProvider.notifier).state = LoginMethod.phone,
                      ),
                      SizedBox(width: 24.w),
                      _buildLoginMethodButton(
                        title: '密码登录',
                        isSelected: loginMethod == LoginMethod.password,
                        onTap: () => ref.read(loginMethodProvider.notifier).state = LoginMethod.password,
                      ),
                    ],
                  ),
                  SizedBox(height: 32.h),

                  // 根据登录方式显示不同的表单
                  if (loginMethod == LoginMethod.phone) ..._buildPhoneLoginForm(sendCodeState, authState),
                  if (loginMethod == LoginMethod.password) ..._buildPasswordLoginForm(authState),
                  
                  SizedBox(height: 16.h),

                  // 其他登录方式
                  Row(
                    children: [
                      const Expanded(child: Divider()),
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 16.w),
                        child: Text(
                          '其他登录方式',
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: AppTheme.textSecondaryColor,
                          ),
                        ),
                      ),
                      const Expanded(child: Divider()),
                    ],
                  ),
                  SizedBox(height: 16.h),

                  // 微信登录按钮 (暂时隐藏)
                  // SizedBox(
                  //   height: 50.h,
                  //   child: OutlinedButton.icon(
                  //     onPressed: authState.isLoading ? null : _loginWithWeChat,
                  //     icon: Icon(
                  //       Icons.wechat,
                  //       color: Colors.green,
                  //       size: 24.r,
                  //     ),
                  //     label: Text(
                  //       '微信登录',
                  //       style: TextStyle(fontSize: 16.sp),
                  //     ),
                  //     style: OutlinedButton.styleFrom(
                  //       foregroundColor: AppTheme.textPrimaryColor,
                  //       side: BorderSide(color: Colors.grey[300]!),
                  //       shape: RoundedRectangleBorder(
                  //         borderRadius: BorderRadius.circular(12.r),
                  //       ),
                  //     ),
                  //   ),
                  // ),
                  SizedBox(height: 24.h),

                  // 用户协议和隐私政策
                  Text.rich(
                    TextSpan(
                      text: '登录即表示您同意',
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: AppTheme.textSecondaryColor,
                      ),
                      children: [
                        TextSpan(
                          text: '《用户协议》',
                          style: TextStyle(
                            color: AppTheme.primaryColor,
                            fontSize: 12.sp,
                          ),
                        ),
                        const TextSpan(text: '和'),
                        TextSpan(
                          text: '《隐私政策》',
                          style: TextStyle(
                            color: AppTheme.primaryColor,
                            fontSize: 12.sp,
                          ),
                        ),
                      ],
                    ),
                    textAlign: TextAlign.center,
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
  
  // 构建登录方式按钮
  Widget _buildLoginMethodButton({
    required String title,
    required bool isSelected,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        children: [
          Text(
            title,
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
              color: isSelected ? AppTheme.primaryColor : AppTheme.textSecondaryColor,
            ),
          ),
          SizedBox(height: 4.h),
          Container(
            width: 20.w,
            height: 3.h,
            decoration: BoxDecoration(
              color: isSelected ? AppTheme.primaryColor : Colors.transparent,
              borderRadius: BorderRadius.circular(2.r),
            ),
          ),
        ],
      ),
    );
  }
  
  // 构建手机号验证码登录表单
  List<Widget> _buildPhoneLoginForm(SendCodeState sendCodeState, AuthState authState) {
    return [
      // 手机号输入框
      TextFormField(
        controller: _phoneController,
        keyboardType: TextInputType.phone,
        style: TextStyle(fontSize: 16.sp),
        decoration: InputDecoration(
          hintText: '请输入手机号',
          prefixIcon: const Icon(Icons.phone_android),
          filled: true,
          fillColor: Colors.grey[100],
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12.r),
            borderSide: BorderSide.none,
          ),
        ),
        inputFormatters: [
          FilteringTextInputFormatter.digitsOnly,
          LengthLimitingTextInputFormatter(11),
        ],
        validator: (value) {
          if (value == null || value.isEmpty) {
            return '请输入手机号';
          }
          if (value.length != 11) {
            return '请输入正确的手机号';
          }
          return null;
        },
      ),
      SizedBox(height: 16.h),

      // 验证码输入框
      Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: TextFormField(
              controller: _codeController,
              keyboardType: TextInputType.number,
              style: TextStyle(fontSize: 16.sp),
              decoration: InputDecoration(
                hintText: '请输入验证码',
                prefixIcon: const Icon(Icons.security),
                filled: true,
                fillColor: Colors.grey[100],
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12.r),
                  borderSide: BorderSide.none,
                ),
              ),
              inputFormatters: [
                FilteringTextInputFormatter.digitsOnly,
                LengthLimitingTextInputFormatter(6),
              ],
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入验证码';
                }
                if (value.length < 4) {
                  return '验证码格式不正确';
                }
                return null;
              },
            ),
          ),
          SizedBox(width: 12.w),
          SizedBox(
            height: 48.h,
            child: ElevatedButton(
              onPressed:
                  _isCountingDown ? null : _sendVerificationCode,
              style: ElevatedButton.styleFrom(
                backgroundColor: AppTheme.primaryColor,
                foregroundColor: Colors.white,
                disabledBackgroundColor: Colors.grey[300],
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12.r),
                ),
              ),
              child: Text(
                _isCountingDown ? '$_countdown秒' : '获取验证码',
                style: TextStyle(fontSize: 14.sp),
              ),
            ),
          ),
        ],
      ),
      SizedBox(height: 24.h),

      // 登录按钮
      SizedBox(
        height: 50.h,
        child: ElevatedButton(
          onPressed: authState.isLoading ? null : _loginWithPhone,
          style: ElevatedButton.styleFrom(
            backgroundColor: AppTheme.primaryColor,
            foregroundColor: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12.r),
            ),
          ),
          child: authState.isLoading
              ? SizedBox(
                  width: 24.r,
                  height: 24.r,
                  child: const CircularProgressIndicator(
                    color: Colors.white,
                    strokeWidth: 2,
                  ),
                )
              : Text(
                  '登录',
                  style: TextStyle(
                      fontSize: 16.sp, fontWeight: FontWeight.bold),
                ),
        ),
      ),
    ];
  }
  
  // 构建账号密码登录表单
  List<Widget> _buildPasswordLoginForm(AuthState authState) {
    return [
      // 用户名/邮箱输入框
      TextFormField(
        controller: _usernameController,
        keyboardType: TextInputType.emailAddress,
        style: TextStyle(fontSize: 16.sp),
        decoration: InputDecoration(
          hintText: '请输入账号/邮箱/手机号',
          prefixIcon: const Icon(Icons.person),
          filled: true,
          fillColor: Colors.grey[100],
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12.r),
            borderSide: BorderSide.none,
          ),
        ),
        validator: (value) {
          if (value == null || value.isEmpty) {
            return '请输入账号';
          }
          return null;
        },
      ),
      SizedBox(height: 16.h),

      // 密码输入框
      TextFormField(
        controller: _passwordController,
        obscureText: !_isPasswordVisible,
        style: TextStyle(fontSize: 16.sp),
        decoration: InputDecoration(
          hintText: '请输入密码',
          prefixIcon: const Icon(Icons.lock),
          suffixIcon: IconButton(
            icon: Icon(
              _isPasswordVisible ? Icons.visibility_off : Icons.visibility,
            ),
            onPressed: () {
              setState(() {
                _isPasswordVisible = !_isPasswordVisible;
              });
            },
          ),
          filled: true,
          fillColor: Colors.grey[100],
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12.r),
            borderSide: BorderSide.none,
          ),
        ),
        validator: (value) {
          if (value == null || value.isEmpty) {
            return '请输入密码';
          }
          if (value.length < 6) {
            return '密码长度不能少于6位';
          }
          return null;
        },
      ),
      SizedBox(height: 16.h),
      
      // 滑块验证码
      Row(
        children: [
          Expanded(
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
              decoration: BoxDecoration(
                color: Colors.grey[100],
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Row(
                children: [
                  Icon(
                    _captchaVerified ? Icons.check_circle : Icons.security,
                    color: _captchaVerified ? Colors.green : Colors.grey,
                    size: 20.r,
                  ),
                  SizedBox(width: 8.w),
                  Text(
                    _captchaVerified ? '验证通过' : '点击进行滑块验证',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: _captchaVerified ? Colors.green : AppTheme.textSecondaryColor,
                    ),
                  ),
                ],
              ),
            ),
          ),
          SizedBox(width: 12.w),
          SizedBox(
            height: 48.h,
            child: ElevatedButton(
              onPressed: _showCaptcha,
              style: ElevatedButton.styleFrom(
                backgroundColor: _captchaVerified ? Colors.green : AppTheme.primaryColor,
                foregroundColor: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12.r),
                ),
              ),
              child: Text(
                _captchaVerified ? '已验证' : '验证',
                style: TextStyle(fontSize: 14.sp),
              ),
            ),
          ),
        ],
      ),
      SizedBox(height: 24.h),

      // 登录按钮
      SizedBox(
        height: 50.h,
        child: ElevatedButton(
          onPressed: authState.isLoading ? null : _loginWithPassword,
          style: ElevatedButton.styleFrom(
            backgroundColor: AppTheme.primaryColor,
            foregroundColor: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12.r),
            ),
          ),
          child: authState.isLoading
              ? SizedBox(
                  width: 24.r,
                  height: 24.r,
                  child: const CircularProgressIndicator(
                    color: Colors.white,
                    strokeWidth: 2,
                  ),
                )
              : Text(
                  '登录',
                  style: TextStyle(
                      fontSize: 16.sp, fontWeight: FontWeight.bold),
                ),
        ),
      ),
    ];
  }
}
